package com.central.apps.handler.project;

import com.central.app.common.base.BaseHandler;
import com.central.app.service.HandlerService;
import com.central.apps.entity.CostAttribute;
import com.central.apps.service.CostAccumulationService;
import com.central.bizcommon.model.flow.FlowNode;
import com.central.bizcommon.model.flow.FlowOpinion;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 处理成本分摊申请业务逻辑
 *
 * @author lidachao
 * @date 2022/10/18
 */
@Component
@Slf4j
public class ProjectCostShareHandler extends BaseHandler {

    @Autowired
    private HandlerService handlerService;
    @Autowired
    private CostAccumulationService costAccumulationService;

    @Override
    public String beforeExcuteFlow(String app, Long id, FlowNode flowNode, FlowOpinion op) throws Exception {
        if("submit".equals(flowNode.getId())) {
            // 查询成本分摊处理信息
            List<Map<String, Object>> list = handlerService.findBySql("select * from gq_procsdealline where pcshid = " + id);

            if (CollectionUtils.isEmpty(list)) {
                return "成本分摊处理信息不能为空";
            } else {
                float totalPencent = 0f;
                for (Map<String, Object> map : list) {
                    float sharePencent = (float) map.get("sharepencent");
                    totalPencent = totalPencent + sharePencent;
                }

                if (totalPencent != 100) {
                    return "成本分摊百分比不等于100%!";
                }
            }
        }

        if("complete".equals(flowNode.getId()) && op.isFlag()) {
            // 查询成本分摊处理信息
            List<Map<String, Object>> list = handlerService.findBySql("select * from gq_procsdealline where pcshid = " + id);

            // 生成成本单
            for (Map<String, Object> map : list) {
                CostAttribute costAttribute = new CostAttribute();
                costAttribute.setName(MapUtils.getString(map, "csdesc"));// 成本单描述
                costAttribute.setProId(MapUtils.getInteger(map, "proid"));// 项目id
                costAttribute.setSubjectNo(MapUtils.getString(map, "subjectno"));// 课题号
                costAttribute.setTotalCost(new BigDecimal(MapUtils.getString(map, "shareamt")));// 总计金额
                costAttribute.setOrderId(MapUtils.getString(map, "id"));// 关联成本分摊单据id
                costAttribute.setOrderNo(MapUtils.getString(map, "csnum"));// 关联成本分摊单据编号
                costAttribute.setCostItemId(MapUtils.getInteger(map, "pbid"));// 预算项id
                costAttribute.setCostSource("成本分摊");

                costAccumulationService.costAccumulation(costAttribute);
            }
        }
        return null;
    }
}
